<template>
  <div class="resident-add-container">
    <el-card class="resident-add-card">
      <template #header>
        <div class="card-header">
          <span>新增住户</span>
          <div class="header-buttons">
            <el-button @click="handleBack">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 选择区域 -->
      <div class="selection-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="社区" required>
              <el-select
                v-model="selectedCommunity"
                placeholder="请选择社区"
                style="width: 100%"
                clearable
                @change="handleCommunityChange"
              >
                <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="楼栋" required>
              <el-select
                v-model="selectedBuilding"
                placeholder="请选择楼栋"
                style="width: 100%"
                clearable
                :disabled="!selectedCommunity"
                @change="handleBuildingChange"
              >
                <el-option
                  v-for="item in buildingList"
                  :key="item.id"
                  :label="item.buildingName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单元" required>
              <el-select
                v-model="selectedUnit"
                placeholder="请选择单元"
                style="width: 100%"
                clearable
                :disabled="!selectedBuilding"
                @change="handleUnitChange"
              >
                <el-option
                  v-for="item in unitList"
                  :key="item.id"
                  :label="item.unitName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="房户" required>
              <el-select
                v-model="selectedHousehold"
                placeholder="请选择房户"
                style="width: 100%"
                clearable
                :disabled="!selectedUnit"
                @change="handleHouseholdChange"
              >
                <el-option
                  v-for="item in householdList"
                  :key="item.id"
                  :label="item.roomNumber"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <!-- 住户信息表单 -->
      <div v-if="selectedHousehold" class="form-area">
        <el-divider content-position="left">住户信息</el-divider>
        
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          @submit.prevent="handleSubmit"
        >
          <!-- 基本信息 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="realName" required>
                <el-input
                  v-model="formData.realName"
                  placeholder="请输入住户姓名"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证件类型" prop="identityType" required>
                <el-select
                  v-model="formData.identityType"
                  placeholder="请选择证件类型"
                  style="width: 100%"
                >
                  <el-option label="身份证" :value="1" />
                  <el-option label="护照" :value="2" />
                  <el-option label="军官证" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身份证件号" prop="identityNo" required>
                <el-input
                  v-model="formData.identityNo"
                  placeholder="请输入身份证件号"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="formData.gender">
                  <el-radio :value="1">男</el-radio>
                  <el-radio :value="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker
                  v-model="formData.birthday"
                  type="date"
                  placeholder="请选择出生日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入手机号码"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="formData.email"
                  placeholder="请输入邮箱地址"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学历" prop="education">
                <el-select
                  v-model="formData.education"
                  placeholder="请选择学历"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="小学" value="小学" />
                  <el-option label="初中" value="初中" />
                  <el-option label="高中" value="高中" />
                  <el-option label="大专" value="大专" />
                  <el-option label="本科" value="本科" />
                  <el-option label="硕士" value="硕士" />
                  <el-option label="博士" value="博士" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职业" prop="profession">
                <el-input
                  v-model="formData.profession"
                  placeholder="请输入职业"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作单位" prop="workUnit">
                <el-input
                  v-model="formData.workUnit"
                  placeholder="请输入工作单位"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input
                  v-model="formData.nativePlace"
                  placeholder="请输入籍贯"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input
                  v-model="formData.emergencyContact"
                  placeholder="请输入紧急联系人"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="紧急联系电话" prop="emergencyPhone">
                <el-input
                  v-model="formData.emergencyPhone"
                  placeholder="请输入紧急联系电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆信息" prop="vehicleInfo">
                <el-input
                  v-model="formData.vehicleInfo"
                  placeholder="请输入车辆信息"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="宠物信息" prop="petInfo">
                <el-input
                  v-model="formData.petInfo"
                  placeholder="请输入宠物信息"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特殊需求" prop="specialNeeds">
                <el-input
                  v-model="formData.specialNeeds"
                  placeholder="请输入特殊需求"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 住户房户关联信息 -->
          <el-divider content-position="left">房户关联信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="住户类型" prop="residentType" required>
                <el-select
                  v-model="formData.residentType"
                  placeholder="请选择住户类型"
                  style="width: 100%"
                >
                  <el-option label="户主" :value="1" />
                  <el-option label="家庭成员" :value="2" />
                  <el-option label="租客" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入住日期" prop="moveInDate">
                <el-date-picker
                  v-model="formData.moveInDate"
                  type="date"
                  placeholder="请选择入住日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="搬出日期" prop="moveOutDate">
                <el-date-picker
                  v-model="formData.moveOutDate"
                  type="date"
                  placeholder="请选择搬出日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同开始日期" prop="contractStartDate">
                <el-date-picker
                  v-model="formData.contractStartDate"
                  type="date"
                  placeholder="请选择合同开始日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同结束日期" prop="contractEndDate">
                <el-date-picker
                  v-model="formData.contractEndDate"
                  type="date"
                  placeholder="请选择合同结束日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="月租金" prop="monthlyRent">
                <el-input-number
                  v-model="formData.monthlyRent"
                  placeholder="请输入月租金"
                  style="width: 100%"
                  :min="0"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="押金" prop="deposit">
                <el-input-number
                  v-model="formData.deposit"
                  placeholder="请输入押金"
                  style="width: 100%"
                  :min="0"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同编号" prop="contractNo">
                <el-input
                  v-model="formData.contractNo"
                  placeholder="请输入合同编号"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  placeholder="请输入备注信息"
                  :rows="3"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              提交
            </el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button @click="handleBack">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 未选择房户时的提示 -->
      <div v-else class="no-selection-tip">
        <el-empty description="请先选择社区、楼栋、单元和房户">
          <template #description>
            <p>请完成上方的四级联动选择，然后填写住户信息</p>
          </template>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'
import { residentApi } from '@/api/resident'

// Router
const router = useRouter()

// Store
const userStore = useUserStore()

// 响应式数据
const submitting = ref(false)
const formRef = ref()

// 选择数据
const selectedCommunity = ref<number>()
const selectedBuilding = ref<number>()
const selectedUnit = ref<number>()
const selectedHousehold = ref<number>()

// 列表数据
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])
const householdList = ref<any[]>([])

// 表单数据
const formData = reactive({
  // 基本信息
  realName: '',
  identityType: 1,
  identityNo: '',
  gender: undefined as number | undefined,
  birthday: undefined as string | undefined,
  phone: '',
  email: '',
  education: '',
  profession: '',
  workUnit: '',
  nativePlace: '',
  emergencyContact: '',
  emergencyPhone: '',
  vehicleInfo: '',
  petInfo: '',
  specialNeeds: '',
  status: 1,
  
  // 住户房户关联信息
  householdId: undefined as number | undefined,
  residentType: 1,
  moveInDate: undefined as string | undefined,
  moveOutDate: undefined as string | undefined,
  contractStartDate: undefined as string | undefined,
  contractEndDate: undefined as string | undefined,
  monthlyRent: undefined as number | undefined,
  deposit: undefined as number | undefined,
  contractNo: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入住户姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  identityType: [
    { required: true, message: '请选择身份证件类型', trigger: 'change' }
  ],
  identityNo: [
    { required: true, message: '请输入身份证件号', trigger: 'blur' },
    { min: 15, max: 20, message: '身份证件号长度在 15 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  residentType: [
    { required: true, message: '请选择住户类型', trigger: 'change' }
  ]
}

// 社区变化处理
const handleCommunityChange = async (communityId: number | undefined) => {
  // 清空下级选择
  selectedBuilding.value = undefined
  selectedUnit.value = undefined
  selectedHousehold.value = undefined
  
  buildingList.value = []
  unitList.value = []
  householdList.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      buildingList.value = Array.isArray(response.data) ? response.data : []
    } catch (error) {
      ElMessage.error('加载楼栋数据失败')
      buildingList.value = []
    }
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number | undefined) => {
  // 清空下级选择
  selectedUnit.value = undefined
  selectedHousehold.value = undefined
  
  unitList.value = []
  householdList.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      unitList.value = Array.isArray(response.data) ? response.data : []
    } catch (error) {
      ElMessage.error('加载单元数据失败')
      unitList.value = []
    }
  }
}

// 单元变化处理
const handleUnitChange = async (unitId: number | undefined) => {
  // 清空下级选择
  selectedHousehold.value = undefined
  
  householdList.value = []
  
  if (unitId) {
    try {
      const response = await householdApi.getHouseholdsByUnit(unitId)
      householdList.value = Array.isArray(response.data) ? response.data : []
    } catch (error) {
      ElMessage.error('加载房户数据失败')
      householdList.value = []
    }
  }
}

// 房户变化处理
const handleHouseholdChange = (householdId: number | undefined) => {
  if (householdId) {
    formData.householdId = householdId
  }
}

// 加载社区列表（根据用户数据权限）
const loadCommunityList = async () => {
  try {
    await userStore.checkAndUpdateCompanyInfo()
    
    const response = await communityApi.getCommunityList({})
    communityList.value = (response.data || []).filter((item: any) => item.id != null)
  } catch (error) {
    ElMessage.error('加载社区数据失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!selectedHousehold.value) {
      ElMessage.error('请先选择房户')
      return
    }
    
    submitting.value = true
    
    // 构建提交数据
    const submitData = {
      ...formData,
      householdId: selectedHousehold.value
    }
    
    await residentApi.addResident(submitData)
    
    ElMessage.success('住户创建成功')
    handleBack()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    realName: '',
    identityType: 1,
    identityNo: '',
    gender: undefined,
    birthday: undefined,
    phone: '',
    email: '',
    education: '',
    profession: '',
    workUnit: '',
    nativePlace: '',
    emergencyContact: '',
    emergencyPhone: '',
    vehicleInfo: '',
    petInfo: '',
    specialNeeds: '',
    status: 1,
    householdId: undefined,
    residentType: 1,
    moveInDate: undefined,
    moveOutDate: undefined,
    contractStartDate: undefined,
    contractEndDate: undefined,
    monthlyRent: undefined,
    deposit: undefined,
    contractNo: '',
    remark: ''
  })
}

// 返回列表
const handleBack = () => {
  router.push('/region/resident')
}

// 组件挂载时初始化
onMounted(() => {
  loadCommunityList()
})
</script>

<style lang="scss" scoped>
.resident-add-container {
  padding: 20px;
  
  .resident-add-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .selection-area {
      margin-bottom: 30px;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 8px;
      
      .el-form-item {
        margin-bottom: 0;
      }
    }
    
    .form-area {
      .el-divider {
        margin: 30px 0 20px 0;
      }
      
      .el-form-item {
        margin-bottom: 20px;
      }
    }
    
    .no-selection-tip {
      text-align: center;
      padding: 60px 0;
      
      p {
        color: #666;
        margin-top: 10px;
      }
    }
  }
}
</style>
